package com.infodms.dms.util;

import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.infodms.dms.bean.AclUserBean;
import com.infodms.dms.common.Constant;
import com.infodms.dms.common.DateUtil;
import com.infodms.dms.common.Utility;
import com.infodms.dms.exception.BizException;
import com.infodms.dms.po.SvoGetnoPO;
import com.infodms.dms.po.TcCodePO;
import com.infodms.dms.po.TmAttachmentPO;
import com.infodms.dms.po.TmBrandPO;
import com.infodms.dms.po.TmBusinessAreaPO;
import com.infodms.dms.po.TmBusinessParaPO;
import com.infodms.dms.po.TmColorPO;
import com.infodms.dms.po.TmDealerPO;
import com.infodms.dms.po.TmOrgPO;
import com.infodms.dms.po.TmReceiveAddressPO;
import com.infoservice.filestore.FileStore;
import com.infoservice.filestore.FileStoreException;
import com.infoservice.po3.POFactory;
import com.infoservice.po3.POFactoryBuilder;
import com.infoservice.po3.bean.PageResult;
import com.infoservice.po3.callbackimpl.POCallBack;
import com.infoservice.po3.core.callback.DAOCallback;
import com.infoservice.po3.core.exceptions.DAOException;


public class CommonUtils {

	private static final int DEF_DIV_SCALE = 2;

	public static final int FIRST_TEN_DAYS = 1;

	public static final int MIDDLE_TEN_DAYS = 2;

	public static final int LAST_TEN_DAYS = 3;

	public static final String HTML_TOKEN_KEY = "HTML_TOKEN";
	
	public static final String SESSION_TOKEN_KEY = "token";
	
	private static POFactory factory = POFactoryBuilder.getInstance();
	
	public static boolean IsOEMCompanyType(Integer ctype) {
		boolean ret = false;
		if (ctype == 10041001)
		{
			ret = true;
		}
		return ret;
	}


	// ------------------- price format handlers -------------------
	private static DecimalFormat priceDecimalFormat = new DecimalFormat("#,##0.00");

	private CommonUtils() {

	}

	/** Formats a Double representing a price into a string
	 * @param price The price Double to be formatted
	 * @return A String with the formatted price
	 */
	public static String formatPrice(Double price) {
		if (price == null)
			return "";
		return formatPrice(price.doubleValue());
	}

	/** Formats a double representing a price into a string
	 * @param price The price double to be formatted
	 * @return A String with the formatted price
	 */
	public static String formatPrice(double price) {

		return priceDecimalFormat.format(price);
	}

	// ------------------- percentage format handlers -------------------
	static DecimalFormat percentageDecimalFormat = new DecimalFormat("##0.##%");

	/** Formats a Double representing a percentage into a string
	 * @param percentage The percentage Double to be formatted
	 * @return A String with the formatted percentage
	 */
	public static String formatPercentage(Double percentage) {
		if (percentage == null)
			return "";
		return formatPercentage(percentage.doubleValue());
	}

	/** Formats a double representing a percentage into a string
	 * @param percentage The percentage double to be formatted
	 * @return A String with the formatted percentage
	 */
	public static String formatPercentage(double percentage) {
		return percentageDecimalFormat.format(percentage);
	}

	//-------------------------------------------  ȡ��
	
	static DecimalFormat percentageIntFormat = new DecimalFormat("##0");

	/** Formats a Double representing a percentage into a string
	 * @param percentage The percentage Double to be formatted
	 * @return A String with the formatted percentage
	 */
	public static String formatIntPercentage(Double percentage) {
		if (percentage == null)
			return "";
		return formatIntPercentage(percentage.doubleValue());
	}

	/** Formats a double representing a percentage into a string
	 * @param percentage The percentage double to be formatted
	 * @return A String with the formatted percentage
	 */
	public static String formatIntPercentage(double percentage) {
		return percentageIntFormat.format(percentage);
	}
	
	
	// ------------------- quantity format handlers -------------------
	static DecimalFormat quantityDecimalFormat = new DecimalFormat("#,##0.###");

	/** Formats an Long representing a quantity into a string
	 * @param quantity The quantity Long to be formatted
	 * @return A String with the formatted quantity
	 */
	public static String formatQuantity(Long quantity) {
		if (quantity == null)
			return "";
		else
			return formatQuantity(quantity.doubleValue());
	}

	/** Formats an int representing a quantity into a string
	 * @param quantity The quantity long to be formatted
	 * @return A String with the formatted quantity
	 */
	public static String formatQuantity(long quantity) {
		return formatQuantity((double) quantity);
	}

	/** Formats an Integer representing a quantity into a string
	 * @param quantity The quantity Integer to be formatted
	 * @return A String with the formatted quantity
	 */
	public static String formatQuantity(Integer quantity) {
		if (quantity == null)
			return "";
		else
			return formatQuantity(quantity.doubleValue());
	}

	/** Formats an int representing a quantity into a string
	 * @param quantity The quantity int to be formatted
	 * @return A String with the formatted quantity
	 */
	public static String formatQuantity(int quantity) {
		return formatQuantity((double) quantity);
	}

	/** Formats a Float representing a quantity into a string
	 * @param quantity The quantity Float to be formatted
	 * @return A String with the formatted quantity
	 */
	public static String formatQuantity(Float quantity) {
		if (quantity == null)
			return "";
		else
			return formatQuantity(quantity.doubleValue());
	}

	/** Formats a float representing a quantity into a string
	 * @param quantity The quantity float to be formatted
	 * @return A String with the formatted quantity
	 */
	public static String formatQuantity(float quantity) {
		return formatQuantity((double) quantity);
	}

	/** Formats an Double representing a quantity into a string
	 * @param quantity The quantity Double to be formatted
	 * @return A String with the formatted quantity
	 */
	public static String formatQuantity(Double quantity) {
		if (quantity == null)
			return "";
		else
			return formatQuantity(quantity.doubleValue());
	}

	/**Formats an double representing a quantity into a string
	 * @param quantity The quantity double to be formatted
	 * @return A String with the formatted quantity
	 */
	public static String formatQuantity(double quantity) {
		return quantityDecimalFormat.format(quantity);
	}

	/**precision math addition operation
	 * @param double param1 and double param2 to addition operation
	 * @return A double value
	 */
	public static double add(double param1, double param2) {
		BigDecimal x1 = new BigDecimal(Double.toString(param1));
		BigDecimal x2 = new BigDecimal(Double.toString(param2));
		return x1.add(x2).doubleValue();
	}

	/**precision math addition operation
	 * @param String param1 and String param2 to addition operation
	 * @return A double value
	 */
	public static double add(String param1, String param2) {
		param1 = makeNull(param1);
		param2 = makeNull(param2);
		BigDecimal x1 = new BigDecimal(param1);
		BigDecimal x2 = new BigDecimal(param2);
		return x1.add(x2).doubleValue();
	}

	/**precision math addition operation
	 * @param list param1 to addition operation
	 * @return A double value
	 */
	public static double add(List param) {
		String n;
		BigDecimal x1;
		BigDecimal x2 = new BigDecimal("0");
		if (param != null && param.size() > 0)
		{
			Iterator iter = param.iterator();
			while (iter.hasNext())
			{
				n = (String) iter.next();
				n = makeNull(n);
				x1 = new BigDecimal(n);
				x2 = x2.add(x1);
			}
		}
		return x2.doubleValue();
	}

	/**precision math addition operation
	 * @param list param1 to addition operation
	 * @return A double value
	 */
	public static double sum(List param) {
		Double n;
		BigDecimal x1;
		BigDecimal x2 = new BigDecimal("0");
		if (param != null && param.size() > 0)
		{
			Iterator iter = param.iterator();
			while (iter.hasNext())
			{
				n = (Double) iter.next();
				if(n!=null) {
					x1 = new BigDecimal(n.toString());
					x2 = x2.add(x1);
				}
				
			}
		}
		return x2.doubleValue();
	}

	/**
	 * precision math subtration operation
	 * @param double param1 and double param2 to subtration operation 
	 * @return A double value
	 */
	public static double sub(double param1, double param2) {
		BigDecimal x1 = new BigDecimal(Double.toString(param1));
		BigDecimal x2 = new BigDecimal(Double.toString(param2));
		return x1.subtract(x2).doubleValue();
	}

	/**
	 * precision math subtration operation
	 * @param String param1 and String param2 to subtration operation 
	 * @return A double value
	 */
	public static double sub(String param1, String param2) {
		param1 = makeNull(param1);
		param2 = makeNull(param2);
		BigDecimal x1 = new BigDecimal(param1);
		BigDecimal x2 = new BigDecimal(param2);
		return x1.subtract(x2).doubleValue();
	}

	/**
	 * precision math multiplication operation
	 * @param double param1 and double param2 to multiplication operation 
	 * @return A double value
	 */
	public static double multiply(double param1, double param2) {
		BigDecimal x1 = new BigDecimal(Double.toString(param1));
		BigDecimal x2 = new BigDecimal(Double.toString(param2));
		return x1.multiply(x2).doubleValue();
	}

	/**
	 * precision math multiplication operation
	 * @param String param1 and double String to multiplication operation 
	 * @return A double value
	 */
	public static double multiply(String param1, String param2) {
		param1 = makeNull(param1);
		param2 = makeNull(param2);
		BigDecimal x1 = new BigDecimal(param1);
		BigDecimal x2 = new BigDecimal(param2);
		BigDecimal p = new BigDecimal("10000");
		x1 = x1.multiply(p);
		x1 = x1.multiply(x2);
		x1 = x1.divide(p, 2, BigDecimal.ROUND_HALF_UP);
		return x1.doubleValue();
	}

	public static double div(double param1, double param2) {

		return div(param1, param2, DEF_DIV_SCALE);

	}

	public static double div(String param1, String param2) {
		param1 = makeNull(param1);
		param2 = makeNull(param2);
		return div(param1, param2, DEF_DIV_SCALE);

	}

	/**
	 * precision math divide operation
	 * @param double param1 and double param2 to divide operation 
	 * @param scale decimal digits
	 * @return A double value
	 */
	public static double div(double param1, double param2, int scale) {

		if (scale < 0)
		{

			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal x1 = new BigDecimal(Double.toString(param1));
		BigDecimal x2 = new BigDecimal(Double.toString(param2));
		return x1.divide(x2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	/**
	 * precision math divide operation
	 * @param String param1 and String param2 to divide operation 
	 * @param scale decimal digits
	 * @return A double value
	 */
	public static double div(String param1, String param2, int scale) {

		if (scale < 0)
		{

			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal x1 = new BigDecimal(param1);
		BigDecimal x2 = new BigDecimal(param2);
		return x1.divide(x2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	/**
	 * precision math round operation
	 * @param double param to round operation 
	 * @param scale decimal digits
	 * @return A double value
	 */
	public static double round(double param1, int scale) {

		if (scale < 0)
		{

			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal b = new BigDecimal(Double.toString(param1));
		BigDecimal one = new BigDecimal("1");
		return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	};

	/**
	 * precision math round operation
	 * @param double param to round operation 
	 * @param scale decimal digits
	 * @return A double value
	 */
	public static double round(String param1, int scale) {
		param1 = makeNull(param1);
		if (scale < 0)
		{

			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal b = new BigDecimal(param1);
		BigDecimal one = new BigDecimal("1");
		return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	};

	/**
	 * calculate tax
	 * @param x1
	 * @param rate
	 * @return
	 */
	public static double calculateTax(String x1, String rate) {
		x1 = makeNull(x1);
		rate = makeNull(rate);
		BigDecimal t = new BigDecimal(x1);
		BigDecimal r = new BigDecimal(rate);
		BigDecimal c = new BigDecimal("1");
		BigDecimal p = new BigDecimal("10000");
		c = r.add(c);
		t = t.multiply(p);
		t = t.divide(c, BigDecimal.ROUND_HALF_UP);
		t = t.multiply(r);
		t = t.divide(p, 2, BigDecimal.ROUND_HALF_UP);
		return t.doubleValue();
	}

	public static double toDouble(String s) {
		s = makeNull(s);
		return Double.valueOf(s).doubleValue();
	}

	/**
	 * conversion A String number to Double
	 * @param param1
	 * @return
	 */
	public static Double parseDouble(String s) {
		s = makeNull(s);
		return Double.valueOf(s);
	}

	/**
	 * conversion A String number with bigDecimal doubleValue
	 * @param s
	 * @return
	 */
	public static Double parseDoubleB(String s) {
		s = makeNull(s);
		BigDecimal x = new BigDecimal(s);
		return new Double(x.doubleValue());
	}

	/**
	 * conversion A String number to float value
	 * @param s
	 * @return
	 */
	public static Float parseFloat(String s) {
		s = makeNull(s);
		return Float.valueOf(s);
	}

	/**
	 * conversion A String number to long value
	 * @param s
	 * @return
	 */
	public static Long parseLong(String s) {
		return Long.valueOf(s);
	}

	/**
	 * conversion A String number to integer value
	 * @param s
	 * @return
	 */
	public static Integer parseInteger(String s) {
		s = makeNull(s);
		return Integer.valueOf(s);
	}

	/**
	 * conversion A String number to date type value
	 * @param s
	 * @return
	 */
	public static Date parseDate(String date) {
		DateFormat df = DateFormat.getDateInstance();
		try
		{
			return df.parse(date);
		}
		catch (ParseException e)
		{
			e.printStackTrace();
		}
		return null;
	}

	// ------------------- null string handlers -------------------
	/** Checks to see if the passed Object is null, if it is returns an empty but non-null string, otherwise calls toString() on the object
	 * @param obj1 The passed Object
	 * @return The toString() of the passed Object if not null, otherwise an empty non-null String
	 */
	public static String makeString(Object obj1) {
		if (obj1 != null)
			return obj1.toString();
		else
			return "";
	}

	/**
	 * Checks to see if the passed string is <code>null</code> string
	 * @param a sring s 
	 * @return an empty non-null String
	 */
	public static String fixedNullString(String s) {
		if (s != null && s.length() > 0)
		{
			if ("null".equalsIgnoreCase(s.trim()))
			{
				return "";
			}
			return s.trim();
		}
		else
		{
			return "";
		}

	}
	
	
	public static String fixedUIString(Object o)
	{
		if (o != null)
		{
			if ("null".equalsIgnoreCase(o.toString()))
			{
				return "";
			}
			return o.toString();
		}
		else
		{
			return "";
		}
	}

	/** Checks to see if the passed string is null, if it is returns an empty but non-null string.
	 * @param string1 The passed String
	 * @return The passed String if not null, otherwise an empty non-null String
	 */
	public static String checkNull(String string1) {
		if (string1 != null)
			return string1;
		else
			return "";
	}
	
	public static String checkNullEx(String string1) {
		if (string1 != null)
			return string1;
		else
			return "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	}
	public static String checkNullEx(Object obj) {
		if (obj != null)
			return obj.toString();
		else
			return "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	}

	/** Checks to see if the passed string is null, if it is returns an empty but non-null string.
	 * @param string1 The passed String
	 * @return The passed String if not null, otherwise an empty non-null String
	 */
	public static String checkNull(Object obj) {
		if (obj != null)
			return obj.toString();
		else
			return "";
	}

	/** Checks to see if the passed string array is null.
	 * @param s The passed String array
	 * @return if the passed String array if not null then return true.
	 */
	public static boolean paramCheck(String[] s) {
		if (s != null && s.length > 0)
			return true;
		else
			return false;
	}

	/** Checks to see if the passed string array is empty "".
	 * @param s The passed String array
	 * @return if the passed String array if not null then return true.
	 */
	public static boolean paramCheck(String s) {
		if (s != null && !"".equals(s) && !"0".equals(s) && !"0.00".equals(s))
			return true;
		else
			return false;
	}

	/** Checks to see if the passed string is a empty string <code>""</code> or a null string.
	 * @param s The passed String 
	 * @return if the passed String if not A <code>""</code> String then return true.
	 */
	public static boolean isEmpty(String str) {
		return str == null || str.trim().length() == 0;
	}

	/** Checks to see if the passed string is null, if it is returns an empty but non-null string.
	 * @param string1 The passed String
	 * @return The passed String if not null, otherwise an empty non-null String
	 */
	public static String makeNull(String string1) {
		if (string1 != null && string1.length() > 0)
			return string1;
		else
			return "";
	}

	/** Checks to see if the passed string is non-null, if it is returns an empty but non-null string.
	 * @param string1 The passed String
	 * @return The passed String if not null, otherwise an empty non-null String
	 */
	public static String trim(String string1) {
		if (string1 != null)
			return string1.trim();
		else
			return "";
	}

	/** 
	 * Replaces all occurances of oldString in mainString with newString
	 * 
	 * @param mainString The original string
	 * @param oldString The string to replace
	 * @param newString The string to insert in place of the old
	 * @return mainString with all occurances of oldString replaced by newString
	 */
	public static String replaceString(String mainString, String oldString, String newString) {
		if (mainString == null)
		{
			return null;
		}
		if (oldString == null || oldString.length() == 0)
		{
			return mainString;
		}
		if (newString == null)
		{
			newString = "";
		}

		int i = mainString.lastIndexOf(oldString);

		if (i < 0)
			return mainString;

		StringBuffer mainSb = new StringBuffer(mainString);

		while (i >= 0)
		{
			mainSb.replace(i, i + oldString.length(), newString);
			i = mainString.lastIndexOf(oldString, i - 1);
		}
		return mainSb.toString();
	}

	/**
	 * Creates a single string from a List of strings seperated by a delimiter.
	 * 
	 * @param list a list of strings to join
	 * @param delim the delimiter character(s) to use. (null value will join with 
	 * no delimiter)
	 * @return a String of all values in the list seperated by the delimiter
	 */
	public static String join(List list, String delim) {
		if (list == null || list.size() < 1)
			return null;
		StringBuffer buf = new StringBuffer();
		Iterator i = list.iterator();

		while (i.hasNext())
		{
			buf.append((String) i.next());
			if (i.hasNext())
				buf.append(delim);
		}
		return buf.toString();
	}

	/**
	 * Splits a String on a delimiter into a List of Strings.
	 * 
	 * @param str the String to split
	 * @param delim the delimiter character(s) to join on (null will split on whitespace)
	 * @return a list of Strings
	 */
	public static List split(String str, String delim) {
		List splitList = null;
		StringTokenizer st = null;

		if (str == null)
			return splitList;

		if (delim != null)
			st = new StringTokenizer(str, delim);
		else
			st = new StringTokenizer(str);

		if (st != null && st.hasMoreTokens())
		{
			splitList = new ArrayList();

			while (st.hasMoreTokens())
				splitList.add(st.nextToken());
		}
		return splitList;
	}

	/**
	 * Format array of string to A PL/SQL String
	 * @param str
	 * @return A formate string with PL/SQL NOT IN syntax 
	 */
	public static String linkStr(String[] str) {
		String temp = "(";
		for (int i = 0; i < str.length; i++)
		{
			if (i == 0)
			{
				temp = temp + "'" + str[i] + "'";
			}
			else
			{
				temp = temp + "," + "'" + str[i] + "'";
			}
		}
		temp = temp + ")";
		return temp;
	}
	
	/**
	 * 将字符串格式成sql形式 
	 * @param str
	 * @param delim
	 * @return
	 */
	public static String strToSql(String str, String delim) {
		StringTokenizer st = null;

		if (str == null)
			return str;

		if (delim != null)
			st = new StringTokenizer(str, delim);
		else
			st = new StringTokenizer(str);
		
		String temp = "(";
		if (st != null && st.hasMoreTokens())
		{			
			while (st.hasMoreTokens()){
				temp = temp + "'" + st.nextToken() + "',";
			}
		}
		if(temp.length()>1){
			temp = temp.substring(0,temp.length()-1) + ")";
		}else{
			temp="";
		}		
		return temp;
	}	

	/**
	 *  将数字字符串格式成sql形式
	 * @param str
	 * @param delim
	 * @return
	 */
	public static String numberToSql(String str, String delim) {
		StringTokenizer st = null;

		if (str == null)
			return str;

		if (delim != null)
			st = new StringTokenizer(str, delim);
		else
			st = new StringTokenizer(str);
		
		String temp = "(";
		if (st != null && st.hasMoreTokens())
		{			
			while (st.hasMoreTokens()){
				temp = temp + st.nextToken() + ",";
			}
		}
		if(temp.length()>1){
			temp = temp.substring(0,temp.length()-1) + ")";
		}else{
			temp="";
		}		
		return temp;
	}	
	
	/**
	 * Formate a Integer num to a string id
	 * @param id
	 * @return A String line number
	 */
	public static String getLineId(int id) {
		String sid = "";
		if (id >= 0 && id <= 9)
		{
			sid = "0" + Integer.toString(id);
		}
		else
		{
			sid = Integer.toString(id);
		}
		return sid;
	}

	/**
	 * parse a double "string"
	 * @param id
	 * @return A string id
	 */
	public static String checkId(String id) {
		String sid = id;
		int i = -1;
		if (id != null && id.length() > 0)
		{
			i = id.indexOf(".");
			if (i != -1)
			{
				sid = id.substring(0, i);
				return sid;
			}
		}
		return sid;
	}

	/**
	 * count the days with compare the firstDate date and the last date 
	 * @param firstDate
	 * @param lastDate
	 * @return A double days
	 */
	public static double compareDateToDays(Date firstDate, Date lastDate) {
		if (firstDate == null || lastDate == null)
			throw new IllegalArgumentException("the paramater is null date.");
		long timeColon1 = firstDate.getTime();
		long timeColon2 = lastDate.getTime();
		long tmpCal = timeColon2 - timeColon1;
		long mm = 24 * 60 * 60 * 1000;
		double days = (double) (tmpCal / mm);
		return Math.abs(days);
	}

	public static boolean checkIsNullStr(String nullStr) {
		boolean ret = false;
		if (nullStr != null && nullStr.length() > 0)
		{
			if (nullStr.equals("null") || "".equals(nullStr.trim()))
			{
				ret = true;
			}
		}
		else
		{
			ret = true;
		}
		return ret;
	}

	/**
	 * whether the part_no is user defined part number
	 * @param partNo
	 * @return true or false
	 */
	public static boolean isUserDefinedPartNo(String partNo) {
		boolean ret = false;
		String marker = null;
		if (partNo != null && !"".equals(partNo))
		{
			if (partNo.length() > 3)
			{
				marker = partNo.substring(0, 3);
				if (marker.equalsIgnoreCase("WZD") || marker.equalsIgnoreCase("DZD"))
				{
					ret = true;
				}
			}
		}
		return ret;
	}

	public static String fixedFormatMoney(String m) {
		String tmp = "";
		if (m != null && m.length() > 0)
		{
			String[] t = m.split(",");
			for (int i = 0; i < t.length; i++)
			{
				tmp += t[i];
			}
			System.out.println(tmp);
		}
		else
		{
			tmp = "0.00";
		}
		return tmp;
	}

	/**
	 *判断是否为合法的TimeStamp格式字符串
	 * @param s
	 * @return
	 */
	public static boolean isValidTimestamp(String s) {
		SimpleDateFormat df = null;
		try
		{
			df = new SimpleDateFormat("yyyy-MM-dd");
			df.parse(s);
			return true;
		}
		catch (Exception e)
		{
			return false;
		}
	}

	public static boolean isValidDate(String s) {
		SimpleDateFormat df = null;
		try
		{
			df = new SimpleDateFormat("yyyy");
			df.parse(s);
			return true;
		}
		catch (Exception e)
		{
			return false;
		}
	}

	public static Date parseDate(String dateString, String format) {
		SimpleDateFormat df = new SimpleDateFormat(format);
		Date result = null;
		try
		{
			result = df.parse(dateString);
		}
		catch (Exception e)
		{
		}
		return result;
	}

	public static Date parseDateTime(String dateString) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//		DateFormat df = DateFormat.getDateTimeInstance();
		Date result = null;
		try
		{
			result = df.parse(dateString);
		}
		catch (Exception e)
		{
		}
		return result;
	}
	
	public static Date parseDTime(String dateString) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		//		DateFormat df = DateFormat.getDateTimeInstance();
		Date result = null;
		try
		{
			result = df.parse(dateString);
		}
		catch (Exception e)
		{
		}
		return result;
	}
	
	public static Date parseHMDate(String dateString) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		//		DateFormat df = DateFormat.getDateTimeInstance();
		Date result = null;
		try
		{
			result = df.parse(dateString);
		}
		catch (Exception e)
		{
		}
		return result;
	}
	
	public static String printDate(Date date) {
		if(date!=null){
		   SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		   return df.format(date);
		}else{
		   return "";
		}

	}

	public static String printDate(String format, Date date) {
		SimpleDateFormat df = new SimpleDateFormat(format);
		return df.format(date);

	}

	public static String printDateTime(Date date) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return df.format(date);

	}

	public static String getYearMonth(Date date) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
		return df.format(date);

	}

	public static long getIntervalDays(Date from, Date to) {
		return (to.getTime() - from.getTime()) / (1000 * 60 * 60 * 24);
	}

	public static String getOriginalFileName(String fileName) {
		int dotPlace = fileName.lastIndexOf(".");
		String firstPart = "";
		String secondPart = "";
		if (dotPlace == -1)
		{
			return fileName;
		}
		else
		{
			firstPart = fileName.substring(0, dotPlace);
			secondPart = fileName.substring(dotPlace + 1, fileName.length());
		}
		dotPlace = firstPart.lastIndexOf(".");
		if (dotPlace == -1)
		{
			return secondPart;
		}
		else
		{
			return firstPart.substring(0, dotPlace + 1) + secondPart;
		}
	}

	public static boolean isNullString(String s) {
		return null == s || s.equals("");
	}

	/**
	 * Tests if this date is before the specified date.
	 * @param   firstDate   a date.
	 * @param   when   a date.
	 * @return  return true or false
	 * @exception NullPointerException if <code>firstDate or when</code> is null.
	 */
	public static boolean dateBefore(Date firstDate, Date when) throws Exception {
		if (firstDate == null || when == null)
		{
			throw new Exception("the date param can not be empty!");
		}
		return firstDate.before(when);
	}

	/**
	 * Tests if this date is after the specified date.
	 * @param   firstDate   a date.
	 * @param   when   a date.
	 * @return  return true or false
	 * @exception NullPointerException if <code>firstDate or when</code> is null.
	 */
	public static boolean dateAfter(Date firstDate, Date when) throws Exception {
		if (firstDate == null || when == null)
		{
			throw new Exception("the date param can not be empty!");
		}
		return firstDate.after(when);
	}

	/**
	 * 判断第一日期（firstDate）减去第二个日期（secondDate）的差 是否 大于 多少天（days）
	 * @param firstDate Date - 第一日期
	 * @param secondDate Date - 第二个日期
	 * @param days  double - 天数
	 * @return  int   1表示大于，0表示等于，-1表示小于
	 */
	public static int compareDate(Date firstDate, Date secondDate, double days) throws Exception {
		if (firstDate == null || secondDate == null)
		{
			throw new Exception("日期不能为空");
		}
		long lFirst = firstDate.getTime();
		long lSecond = secondDate.getTime();
		long tmp = lFirst - lSecond;
		long lDays = (long) (days * 24 * 60 * 60 * 1000);
		if (tmp > lDays)
		{
			return 1;
		}
		else
		{
			if (tmp == lDays)
			{
				return 0;
			}
			else
			{
				return -1;
			}
		}

	}

	/**
	 * 根据传入日期来判断该日期是上旬、中旬还是下旬
	 * @param date 
	 * @return 
	 * @throws IllegalArgumentException 
	 */
	public static int get10DaysSpanType(Date date) throws IllegalArgumentException {
		int returnValue = 0;
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);

		int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);

		if (dayOfMonth >= 1 && dayOfMonth <= 10)
			returnValue = FIRST_TEN_DAYS;
		else if (dayOfMonth > 10 && dayOfMonth <= 20)
			returnValue = MIDDLE_TEN_DAYS;
		else if (dayOfMonth > 20 && dayOfMonth <= 31)
			returnValue = LAST_TEN_DAYS;
		else
			throw new IllegalArgumentException("the paramater is not a valid date.");

		return returnValue;
	}

	/**
	 *根据传入日期来判断该日期是上旬、中旬还是下旬
	 * @param dateStr
	 * @return
	 * @throws IllegalArgumentException
	 */
	public static int get10DaysSpanType(String dateStr) throws IllegalArgumentException {
		DateFormat format = DateFormat.getDateInstance();
		Date date;
		try
		{
			date = format.parse(dateStr);
		}
		catch (ParseException e)
		{
			throw new IllegalArgumentException("the paramater is not a valid date string.");
		}
		return get10DaysSpanType(date);
	}

	/**
	 *  取得时间在月份中对应的天数
	 * @param date
	 * @return
	 */
	public static int getMonthDays(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
	}

	/**
	 * 将从fromDate 到 toDate 之间（包括 fromDate 和 toDate)的时间放到一个list中返回
	 * @param fromDate
	 * @param toDate
	 * @return
	 */
	public static List getDaysList(Date fromDate, Date toDate) {
		ArrayList list = new ArrayList();
		Calendar cal = Calendar.getInstance();
		cal.setTime(fromDate);
		while (fromDate.before(toDate))
		{
			list.add(fromDate);
			cal.add(Calendar.DATE, 1);
			fromDate = cal.getTime();
		}
		list.add(toDate);
		return list;
	}

	/**
	 * 如果日期是一个月份的第10天、第20天或最后一天，则返回true，否则返回false
	 * @param date
	 * @return
	 */
	public static boolean isLastTenDays(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		if (cal.getActualMaximum(Calendar.DAY_OF_MONTH) == cal.get(Calendar.DATE))
			return true;
		if (cal.get(Calendar.DATE) == 10)
			return true;
		if (cal.get(Calendar.DATE) == 20)
			return true;
		return false;
	}

	public static Date currentDateTime() {
		return Calendar.getInstance().getTime();
	}

	public static Date getLastDateOfMonth(Date dateTime) {
		Calendar cal1 = Calendar.getInstance();

		cal1.setTime(dateTime);
		Calendar cal2 = new GregorianCalendar(cal1.get(Calendar.YEAR), cal1.get(Calendar.MONTH),
				cal1.getActualMaximum((Calendar.DAY_OF_MONTH)));

		return cal2.getTime();
	}

	public static int getDayOfWeek(Date dateTime) {

		Calendar cal = Calendar.getInstance();
		cal.setTime(dateTime);

		return cal.get(Calendar.DAY_OF_WEEK);
	}

	/**
	 * @param currentDate
	 * @param day
	 * @return Date
	 * @description 日期增加天数
	 */
	public static Date addDay(Date currentDate, int day) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(currentDate);
		calendar.add(Calendar.DAY_OF_MONTH, day);
		return calendar.getTime();
	}

	/**
	 * @param currentDate
	 * @param hour
	 * @return Date
	 * @description 日期时间增加小时
	 */
	public static Date addHour(Date currentDate, int hour) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(currentDate);
		calendar.add(Calendar.HOUR, hour);
		return calendar.getTime();
	}
	
	/**
	 *  判断是否是负数
	 * @param n
	 * @return
	 */
	public static boolean isMinus(Double n)
	{
		boolean result = false;
		if (n != null && n<0)
		{
			result = true;
		}
		return result;
	}
	
    /**
     * ȡ���取数字绝对值
     * @param n
     * @return
     */
	public static Double abs(Double n)
	{
		if (n!=null && n<0)
		{
			return Math.abs(n.doubleValue());
		}
		else if(n!=null && n > 0)
		{
			return n;
		}else{
			return new Double(0.0d);
		}
	}
	
	/**
	 * 显式转换为负长整型值
	 * @param id
	 * @return
	 */
	public static Long toMinus(Long id)
	{
		String key;
		Long l=0L;
		if (id == null)
		{
			throw new IllegalArgumentException("is not a long number");
		}
		key = "-"+id.toString();
		l = new Long(key);
		return l;
	}
	
	/**
	 * 显式转换为负浮点数
	 * @param id
	 * @return
	 */
	public static Double toMinus(Double id)
	{
		String key;
		Double l=0.0;
		if (id == null)
		{
			throw new IllegalArgumentException("is not a double number");
		}
		key = "-"+id.toString();
		l = new Double(key);
		return l;
	}
	
	/**
	 * 判断字符串是否是数字
	 * @param s
	 * @return
	 */
	public static boolean isNumber(String s)
	{
		boolean ret =true;
		Pattern pattern = Pattern.compile("[0-9+./+-/]");
	    char[] ss = s.toCharArray();
	    for (int i=0;i<ss.length; i++)
	    {
	    	Matcher isNum = pattern.matcher(String.valueOf(ss[i]));
	    	if (!isNum.find())
	    	{
	    		ret = false;
	    		break;
	    	}
	    }
		return ret;
	}
	/**
	 * 处理Double类型数据的四舍五入以及小数位精确到第N位
	 * @param d  需要处理的double类型的数据
	 * @param decimalNum  需要精确的小数位数
	 */
	public static String printDouble(double d,int decimalNum){
		NumberFormat numberFormat = NumberFormat.getNumberInstance();
		numberFormat.setMaximumFractionDigits(decimalNum);
		numberFormat.setGroupingUsed(false);
		
		return numberFormat.format(d);
	}	
	public static void main(String[] args) {
		//test case
		System.out.println(CommonUtils.isNumber("-9"));
	}
	
	/**
	 * 格式化金钱数位XXX,XXX.00
	 * @param num 需要格式化的金钱数
	 * @param decimalNum 小数精确位数
	 * @param defaultValue 当需要格式化数位空时，默认返回值,null 则返回0
	 * @return String
	 */
	public static String currencyFormat(Double num,int decimalNum,String defaultValue){
		
		String fmRes = "0";
		
		if(num==null){
			if(defaultValue!=null)
				fmRes = defaultValue;
			return fmRes;
		}else if(num==0){
			return fmRes;
		}
		NumberFormat nf = NumberFormat.getInstance(Locale.CHINA);
		nf.setMinimumFractionDigits(decimalNum);
		nf.setMaximumFractionDigits(decimalNum);
		
		fmRes = nf.format(num);
		
		return fmRes;
	}
	
	/**
	 * 格式化金钱数位XXX,XXX.00
	 * @param num 需要格式化的金钱数
	 * @param decimalNum 小数精确位数
	 * @param defaultValue 当需要格式化数位空时，默认返回值,null 则返回0
	 * @return String
	 */
	public static String currencyFormat(Float num,int decimalNum,String defaultValue){
		
		String fmRes = "0";
		
		if(num==null){
			if(defaultValue!=null)
				fmRes = defaultValue;
			return fmRes;
		}else if(num==0){
			return fmRes;
		}
		NumberFormat nf = NumberFormat.getInstance(Locale.CHINA);
		nf.setMinimumFractionDigits(decimalNum);
		nf.setMaximumFractionDigits(decimalNum);
		
		fmRes = nf.format(num);
		
		return fmRes;
	}
	
	public static Float floatValue(Double d){
	    if(d!=null){
	       return (Float)d.floatValue();
	    }
	    return null;
	}
	
	public static Double doubleValue(Float f){
	    if(f!=null){
	       return (Double)f.doubleValue();
	    }
	    return null;
	}
	
	public static String valueOf(Integer integer){
		if(integer != null){
			return String.valueOf(integer);
		}else{
			return null;
		}
	}
	
	public static String formatString(String str){
		String rv = "";
		if(str!=null){
			if(str.contains(";")){
				rv = str.replace(";", "<br>");
			}else{
				rv = str;
			}
		}
		return rv;
	}
	/**
	 * 将字符串格式成sql like 的形式
	 * @param str
	 * @param delim
	 * @param column
	 * @return
	 */
	public static String strToSqlLike(String str, String delim,String column) {
		String [] strArr = null;
		String strLike = null;
		String strNull = " 1 = 1";
		//如果需要处理的字符串为空，返回
		if (str == null||str.trim().length()==0){
			return strNull;
		}
		if(delim==null||delim.trim().length()==0){
			return strNull;
		}else{
			strArr = str.split(delim);
		}
		if(column==null||column.trim().length()==0){
			return strNull;
		}
		StringBuffer sb = new StringBuffer("(");
		//循环生成字符串
		for(int i=0;i<strArr.length;i++){
			if(strArr[i].trim().length()>0){
				sb.append(column);
				sb.append(" like '%");
				sb.append(strArr[i].trim().toUpperCase());
				sb.append("%' or ");
			}
		}
		if(sb.length()>1){
            return sb.append(")").toString().replaceAll(" or \\)",")");
		}else{
			return strNull;
		}
	}
	
	/**
	 * 将字符串格式成sql like 的形式
	 * @param str
	 * @param delim
	 * @param column
	 * @return
	 */
	public static boolean isInnerNetwork(String ip) {
		String allowIpRegex = "(127[.]0[.]0[.]1)|(localhost)|" +
							  "(10[.]\\d{1,3}[.]\\d{1,3}[.]\\d{1,3})|" +
							  "(172[.]((1[6-9])|(2\\d)|(3[01]))[.]\\d{1,3}[.]\\d{1,3})|" +
							  "(192[.]168[.]\\d{1,3}[.]\\d{1,3})"; 
		//Pattern pattern = Pattern.compile(allowIpRegex);
		return Pattern.matches(allowIpRegex,ip);
	}
	
	/**
	 * 查询出所有有效的品牌信息
	 * @return
	 */
	public static List<TmBrandPO> findAllBrands(){			
		TmBrandPO po = new TmBrandPO();
		//查询有效的品牌
		po.setStatus(Constant.STATUS_ENABLE);
		return factory.select(po);
	}
	//modify by xiayanpeng begin 查询出所有有效的业务范围信息
	public static List<TmBusinessAreaPO> findAllBusinessAreaPO(Long companyId){			
		TmBusinessAreaPO po = new TmBusinessAreaPO();
		//查询有效的品牌
		po.setStatus(Constant.STATUS_ENABLE);
	    po.setCompanyId(companyId);
		return factory.select(po);
	}
	//modify by xiayapeng end
	
	/**
	 * 根据品牌ID查询出指定的有效的品牌信息
	 * @param brandIds : 以String的形式传递多个或单个品牌ID
	 * @return
	 */
	public static List<TmBrandPO> findAllBrands(String brandIds){
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT T.BRAND_ID,T.BRAND_NAME,T.ENGLISH_NAME,T.BRAND_CODE,T.REMARK,T.BUSINESS_TYPE,T.BILL_TOTAL,");
		sb.append("T.STATUS,T.CREATE_DATE,T.UPDATE_DATE,T.CREATE_BY,T.UPDATE_BY,T.OLD_MODEL_SIFT FROM TM_BRAND T");
		sb.append(" WHERE T.STATUS = ?");
		sb.append(" AND T.BRAND_ID IN (" + brandIds + ")");
		sb.append(" ORDER BY T.BRAND_NAME ");
		
		List<Object> params = new ArrayList<Object>();
		params.add(Constant.STATUS_ENABLE);
		
		return factory.select(sb.toString(), params,new DAOCallback<TmBrandPO>() {
			public TmBrandPO wrapper(ResultSet rs, int idx){
				TmBrandPO po = new TmBrandPO();
				try {
					po.setBrandId(rs.getLong("BRAND_ID"));
					po.setBrandName(rs.getString("BRAND_NAME"));
					po.setEnglishName(rs.getString("ENGLISH_NAME"));
					po.setBrandCode(rs.getString("BRAND_CODE"));
					po.setRemark(rs.getString("REMARK"));
					po.setBusinessType(rs.getString("BUSINESS_TYPE"));
					po.setBillTotal(rs.getString("BILL_TOTAL"));
					po.setStatus(rs.getInt("STATUS"));
					po.setCreateDate(rs.getTimestamp("CREATE_DATE"));
					po.setUpdateDate(rs.getTimestamp("UPDATE_DATE"));
					po.setCreateBy(rs.getLong("CREATE_BY"));
					po.setUpdateBy(rs.getLong("UPDATE_BY"));
					po.setOldModelSift(rs.getInt("OLD_MODEL_SIFT"));
				} catch (SQLException e) {
					e.printStackTrace();
				}
				return po;
			}
		});
	}
	/**
	 * 根据组织ID查询用户信息
	 * @param userId
	 * @param orgId
	 * @return
	 */
	public static PageResult<Map<String,Object>> getUserInfoByOrgID(Long orgId) {
		StringBuffer sql = new StringBuffer("");
		sql.append("SELECT tu.user_id, tu.acnt, tu.NAME, tu.email \n");
		sql.append("  FROM tc_user tu, tr_user_pose rp, tc_pose tp \n");
		sql.append(" WHERE tu.user_id = rp.user_id \n");
		sql.append("   AND rp.pose_id = tp.pose_id \n");
		if(orgId != null)
			sql.append("   AND tp.org_id = "+orgId+" \n");
		sql.append("   AND tu.user_status = "+Constant.STATUS_ENABLE+" \n");
		return factory.pageQuery(sql.toString(), null,new DAOCallback<Map<String,Object>>() {
			public Map<String,Object> wrapper(ResultSet rs, int idx){
				return PersisUtil.getMap("CommonUtils.getUserInfoByOrgID",rs);
			}
		}, 9999, 1);
	}
	/**
	 * 根据组织关系ID查出所有有效的品牌
	 * @return
	 */
	public static List<TmBrandPO> findAllBrands(Long orgId){
		
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT T.* FROM TM_BRAND T,TM_ORG_BUSINESS_AREA O ");
		sb.append(" WHERE T.BRAND_ID = O.BRAND_ID ");
		sb.append(" AND T.STATUS = ? ");
		sb.append(" AND O.ORG_ID = ? ");
		sb.append(" ORDER BY T.BRAND_NAME ");
		
		List<Object> params = new ArrayList<Object>();
		params.add(Constant.STATUS_ENABLE);
		params.add(orgId);
		
		return factory.select(sb.toString(), params,new DAOCallback<TmBrandPO>() {
			public TmBrandPO wrapper(ResultSet rs, int idx){
				TmBrandPO po = new TmBrandPO();
				try {
					po.setBrandId(rs.getLong("BRAND_ID"));
					po.setBrandName(rs.getString("BRAND_NAME"));
					po.setEnglishName(rs.getString("ENGLISH_NAME"));
					po.setBrandCode(rs.getString("BRAND_CODE"));
					po.setRemark(rs.getString("REMARK"));
					po.setBusinessType(rs.getString("BUSINESS_TYPE"));
					po.setBillTotal(rs.getString("BILL_TOTAL"));
					po.setStatus(rs.getInt("STATUS"));
					po.setCreateDate(rs.getTimestamp("CREATE_DATE"));
					po.setUpdateDate(rs.getTimestamp("UPDATE_DATE"));
					po.setCreateBy(rs.getLong("CREATE_BY"));
					po.setUpdateBy(rs.getLong("UPDATE_BY"));
					po.setOldModelSift(rs.getInt("OLD_MODEL_SIFT"));
				} catch (SQLException e) {
					e.printStackTrace();
				}
				return po;
			}
		});
	}
	
	
	/**
	 * 根据组织关系ID查出所有有效的品牌
	 * @return
	 */
	public static List<TmBrandPO> findAllBrandsForActivity(Long orgId,String brandIds){
		
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT T.* FROM TM_BRAND T,TM_ORG_BUSINESS_AREA O ");
		sb.append(" WHERE T.BRAND_ID = O.BRAND_ID ");
		sb.append(" AND T.STATUS = ? ");
		sb.append(" AND O.ORG_ID = ? ");
		sb.append(" AND T.BRAND_ID IN (");
		sb.append(brandIds);
		sb.append(")");
		sb.append(" ORDER BY T.BRAND_NAME ");
		
		List<Object> params = new ArrayList<Object>();
		params.add(Constant.STATUS_ENABLE);
		params.add(orgId);
		
		return factory.select(sb.toString(), params,new DAOCallback<TmBrandPO>() {
			public TmBrandPO wrapper(ResultSet rs, int idx){
				TmBrandPO po = new TmBrandPO();
				try {
					po.setBrandId(rs.getLong("BRAND_ID"));
					po.setBrandName(rs.getString("BRAND_NAME"));
					po.setEnglishName(rs.getString("ENGLISH_NAME"));
					po.setBrandCode(rs.getString("BRAND_CODE"));
					po.setRemark(rs.getString("REMARK"));
					po.setBusinessType(rs.getString("BUSINESS_TYPE"));
					po.setBillTotal(rs.getString("BILL_TOTAL"));
					po.setStatus(rs.getInt("STATUS"));
					po.setCreateDate(rs.getTimestamp("CREATE_DATE"));
					po.setUpdateDate(rs.getTimestamp("UPDATE_DATE"));
					po.setCreateBy(rs.getLong("CREATE_BY"));
					po.setUpdateBy(rs.getLong("UPDATE_BY"));
					po.setOldModelSift(rs.getInt("OLD_MODEL_SIFT"));
				} catch (SQLException e) {
					e.printStackTrace();
				}
				return po;
			}
		});
	}
	
	/**
	 * 根据组织关系ID查出所有有效的品牌
	 * @return
	 */
public static List<TmOrgPO> findAgentAndDistribution(Long orgId){
		
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT O.ORG_ID,O.ORG_NAME FROM TM_ORG O ");
		sb.append(" WHERE O.ORG_ID = ");
		sb.append(orgId);
		sb.append(" UNION ");
		sb.append("SELECT O.ORG_ID,O.ORG_NAME FROM TM_ORG O ");
		sb.append(" WHERE O.PARENT_ORG_ID = ");
		sb.append(orgId);
		
		List<Object> params = new ArrayList<Object>();
		
		return factory.select(sb.toString(), params,new DAOCallback<TmOrgPO>() {
			public TmOrgPO wrapper(ResultSet rs, int idx){
				TmOrgPO po = new TmOrgPO();
				try {
					po.setOrgId(rs.getLong("ORG_ID"));
					po.setOrgName(rs.getString("ORG_NAME"));
				} catch (SQLException e) {
					e.printStackTrace();
				}
				return po;
			}
		});
	}


	public static List<TcCodePO> findTcCodeByType(Integer type){
	
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT CODE_ID,CODE_DESC,TYPE_NAME FROM TC_CODE ");
		sb.append(" WHERE TYPE = ");
		sb.append(type);
	
		List<Object> params = new ArrayList<Object>();
	
		return factory.select(sb.toString(), params,new DAOCallback<TcCodePO>() {
			public TcCodePO wrapper(ResultSet rs, int idx){
				TcCodePO po = new TcCodePO();
				try {
					po.setCodeId(rs.getString("CODE_ID"));
					po.setCodeDesc(rs.getString("CODE_DESC"));
					po.setTypeName(rs.getString("TYPE_NAME"));
				} catch (SQLException e) {
					e.printStackTrace();
				}
				return po;
			}
		});
}
		
	/**
	 * BY 代理商ID 查询出指定代理商信息
	 * @param dealerId 代理商ID : dealerId
	 * @return
	 */
	public static TmDealerPO getDealerInfoByDealerId(Long dealerId){
		if(null != dealerId && !"".equals(dealerId)){
			TmDealerPO po = new TmDealerPO();
			po.setDealerId(dealerId);
			List<TmDealerPO> list = factory.select(po);
			if(null != list && list.size() > 0){
				po = list.get(0);
			}
			return po;
		}else{
			return null;
		}		
	}
	
	
	/**
	 * 根据组织关系ID查出对应的经销商
	 * @return
	 */
	public static TmDealerPO findAllDealers(Long orgId){
		
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT T.* FROM TM_DEALER T,TM_DEALER_ORG_RELATION D ");
		sb.append(" WHERE T.DEALER_ID = D.DEALER_ID ");
		sb.append(" AND T.STATUS = ? ");
		sb.append(" AND D.ORG_ID = ? ");
		sb.append(" ORDER BY T.DEALER_ID ");
		
		List<Object> params = new ArrayList<Object>();
		params.add(Constant.STATUS_ENABLE);
		params.add(orgId);
		
		List<TmDealerPO> list = factory.select(sb.toString(), params,new DAOCallback<TmDealerPO>() {
			public TmDealerPO wrapper(ResultSet rs, int idx){
				TmDealerPO po = new TmDealerPO();
				try {
					po.setDealerId(rs.getLong("DEALER_ID"));
					po.setCompanyId(rs.getLong("COMPANY_ID"));
					po.setDealerType(rs.getInt("DEALER_TYPE"));
					po.setDealerCode(rs.getString("DEALER_CODE"));
					po.setDealerName(rs.getString("DEALER_NAME"));
					po.setDealerShortname(rs.getString("DEALER_SHORTNAME"));
					po.setStatus(rs.getInt("STATUS"));
					//po.setProvinceId(rs.getInt("PROVINCE_ID"));				
					//po.setCityId(rs.getInt("CITY_ID"));
					po.setZipCode(rs.getString("ZIP_CODE"));
					po.setAddress(rs.getString("ADDRESS"));	
					po.setPhone(rs.getString("PHONE"));
					po.setFaxNo(rs.getString("FAX_NO"));				
					po.setLinkMan(rs.getString("LINK_MAN"));	
					//po.setTaxAccounts(rs.getString("TAX_ACCOUNTS"));		
					//po.setReciveAccount(rs.getString("RECIVE_ACCOUNT"));	
					po.setBeginBank(rs.getString("BEGIN_BANK"));
					//po.setComLevel(rs.getInt("COM_LEVEL"));
					//po.setLevelType(rs.getInt("LEVEL_TYPE"));			
					po.setRemark(rs.getString("REMARK"));
					//po.setQadCode(rs.getString("QAD_CODE"));	
					//po.setAgentCode(rs.getString("AGENT_CODE"));	
					po.setCreateDate(rs.getTimestamp("CREATE_DATE"));	
					po.setUpdateDate(rs.getTimestamp("UPDATE_DATE"));
					po.setCreateBy(rs.getLong("CREATE_BY"));	
					po.setUpdateBy(rs.getLong("UPDATE_BY"));
					//po.setSaleArea(rs.getString("SALE_AREA"));
					//po.setStockSet(rs.getString("STOCK_SET"));					
					//po.setIsMonopoly(rs.getInt("IS_MONOPOLY"));					
					//po.setAgType(rs.getInt("AG_TYPE"));					
				} catch (SQLException e) {
					e.printStackTrace();
				}
				return po;
			}
		});
		
		if(list.size() > 0){
			return list.get(0);
		}else{
			return null;
		}
	}
	
	/**
	 * 根据父组织ID，查询分销商信息
	 * @param parentOrgId
	 * @return
	 */
	public static List<TmOrgPO> getFxOrgIDByParentId(Long parentOrgId) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT org.org_id, org.org_code, org.org_name, org.org_type, org.company_id \n");
		sql.append("  FROM tm_org org, tm_dealer dea, tm_dealer_org_relation dor \n");
		sql.append(" WHERE org.org_id = dor.org_id \n");
		sql.append("   AND dea.dealer_id = dor.dealer_id \n");
		//modified by andy.ten@tom.com 去掉分销
		//sql.append("   AND org.org_type = "+Constant.ORG_TYPE_DISTRIBUTION+" \n");
		sql.append("   AND org.status = "+Constant.STATUS_ENABLE+" \n");
		sql.append("   AND dea.status = "+Constant.STATUS_ENABLE+" \n");
		sql.append("   AND org.parent_org_id = "+parentOrgId+" \n");
		
		return factory.select(sql.toString(), null,new DAOCallback<TmOrgPO>() {
			public TmOrgPO wrapper(ResultSet rs, int idx){
				TmOrgPO po = new TmOrgPO();
				try {
					po.setOrgId(rs.getLong("org_id"));
					po.setOrgCode(rs.getString("org_code"));
					po.setOrgName(rs.getString("org_name"));
					po.setOrgType(rs.getInt("org_type"));
					po.setCompanyId(rs.getLong("company_id"));
				} catch (SQLException e) {
					e.printStackTrace();
				}
				return po;
			}
		});
	}
	
	/**
	 * 查询出所有有效的颜色信息
	 * @param type
	 * @return
	 */
	public static List<TmColorPO> findAllColors(){
		TmColorPO po = new TmColorPO();
		po.setStatus(Constant.STATUS_ENABLE);
		return factory.select(po);
	}
	
	/**
	 * 查询出有效的公共参数类型
	 * @param TcCodePO
	 * @return
	 */
	public static List<TcCodePO> findAllPublicParamCodes(TcCodePO po){
		StringBuffer sb = new StringBuffer();		
		sb.append("SELECT DISTINCT T.TYPE,T.TYPE_NAME FROM TC_CODE T WHERE 1=1 ");
			
		List<Object> params = new ArrayList<Object>();
		if(null != po.getStatus() && !"".equals(po.getStatus())){
			//根据传递的参数查询：有效无效
			params.add(po.getStatus());
			sb.append(" AND T.STATUS = ? ");
		}else{
			//默认查询有效数据
			params.add(Constant.STATUS_ENABLE);
			sb.append(" AND T.STATUS = ? ");
		}
		//查询是否可以修改
		if(null != po.getCanModify() && !"".equals(po.getCanModify())){
			params.add(po.getCanModify());
			sb.append(" AND T.CAN_MODIFY = ? ");
		}		
		sb.append(" ORDER BY T.TYPE_NAME");		
		
		return factory.select(sb.toString(), params,new DAOCallback<TcCodePO>() {
			public TcCodePO wrapper(ResultSet rs, int idx){
				TcCodePO po = new TcCodePO();
				try {
					po.setType(rs.getString("TYPE"));
					po.setTypeName(rs.getString("TYPE_NAME"));
				} catch (SQLException e) {
					e.printStackTrace();
				}
				return po;
			}
		});
	}
	
	/**
	 * 根据业务ID，业务类型查询所有相关附件
	 * @param id  业务ID
	 * @param tableName  业务类型即表名  
	 * @return
	 * create by lwj 2009-12-22
	 */
	public static List<TmAttachmentPO> getAttachmentList(Long id,String tableName) {
		TmAttachmentPO po = new TmAttachmentPO();
		po.setBusinessId(id);
		po.setAttachmentType(tableName);
		return factory.select(po);
	}
	/**
	 * 根据附件ID删除附件
	 * @param id
	 * @return
	 * @throws FileStoreException 
	 */
	public static int delAttachment(Long id,String fileId) throws FileStoreException {
		FileStore fs = FileStore.getInstance();
		fs.delete(fileId);
		TmAttachmentPO po = new TmAttachmentPO();
		po.setAttachmentId(id);
		return factory.delete(po);
	}
	/**
	 * 根据业务参数类型代码取得业务参数列表
	 * @param typeCode
	 * @return
	 */
	public static List<TmBusinessParaPO> getBussinessParaByType(String typeCode) {
		TmBusinessParaPO po = new TmBusinessParaPO();
		po.setTypeCode(Integer.valueOf(typeCode));
		return factory.select(po);
	}
	/**
	 * 根据业务参数代码返回参数值
	 * @param paraId
	 * @return
	 */
	public static String getBussinessParaByCode(String paraId) {
		TmBusinessParaPO po = new TmBusinessParaPO();
		po.setParaId(Integer.valueOf(paraId));
		List<TmBusinessParaPO> list = factory.select(po);
		if(list != null && list.size() > 0) { 
			po = list.get(0);
			return po.getParaValue();
		} else {
			return "";
		}
	}
	/**
	 * 根据ORGID返回收车地点
	 * @param orgId
	 * @return
	 */
	public static List<TmReceiveAddressPO> getAddressByOrgId(Long orgId) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT t.address_id, t.TAKECAR_SITE_NAME receive_address \n");
		sql.append("  FROM tm_receive_address t, tm_dealer_org_relation dor, tm_org org \n");
		sql.append(" WHERE t.dealer_id = dor.dealer_id \n");
		sql.append("   AND dor.org_id = org.org_id \n");
		sql.append("   AND org.org_id = "+orgId+" \n");
		
		return factory.select(sql.toString(), null,new DAOCallback<TmReceiveAddressPO>() {
			public TmReceiveAddressPO wrapper(ResultSet rs, int idx){
				TmReceiveAddressPO po = new TmReceiveAddressPO();
				try {
					po.setAddressId(rs.getLong("address_id"));
					po.setReceiveAddress(rs.getString("receive_address"));
				} catch (SQLException e) {
					e.printStackTrace();
				}
				return po;
			}
		});
	}
	/**
	 * 根据规则返回编号
	 * @param dateType 日期格式
	 * @param orgId 如果需要DEALERCODE则传ORGID
	 * @param sclass 根据品牌得到的头字母类似T/Q/P
	 * @param flag 流水号前的分隔符
	 * @param num 流水号初始数
	 * @return
	 * create by lwj
	 */
	public static String getNoByRules(String sclass,Long orgId,String dateType,String flag,int num) {
		StringBuffer returnNo = new StringBuffer("");
		StringBuffer date = new StringBuffer("");
		String year = new String("");
		String month = new String("");
		String day = new String("");
		SvoGetnoPO spo = new SvoGetnoPO();
		TmDealerPO dpo = null;
		
		spo.setSclass(sclass);
		if(orgId != null) {
			dpo = CommonUtils.findAllDealers(orgId);
			spo.setDealerCode(dpo.getDealerCode());
		}
		if(dateType != null && !dateType.equals("")) {
			Date aDate = new Date(System.currentTimeMillis()); 
			year = DateUtil.getYearByDate(aDate);
			month = DateUtil.getMonthByDate(aDate);
			day = DateUtil.getDayByDate(aDate);
			if(dateType.equals("YYYY"))
				date.append(year);
			else if(dateType.equals("YY"))
				date.append(year.substring(2,4));
			else if(dateType.equals("YYYYMM"))
				date.append(year).append(month);
			else if(dateType.equals("YYMM"))
				date.append(year.substring(2,4)).append(month);
			else if(dateType.equals("YYYYMMDD"))
				date.append(year).append(month).append(day);
			else if(dateType.equals("YYMMDD"))
				date.append(year.substring(2,4)).append(month).append(day);
			spo.setStime(date.toString());
		}
//		查询SVO编号表中当前年月的流水号，FOR UPDATE防止并发
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT     nums \n");
		sql.append("      FROM svo_getno \n");
		sql.append("     WHERE sclass = '"+ sclass +"' AND stime = '" + spo.getStime()+"'  \n");
		if(orgId != null)
			sql.append("	   AND dealer_code = '"+spo.getDealerCode()+"' \n");
		sql.append("FOR UPDATE \n");
		List<Integer> list = factory.select(sql.toString(), null, new DAOCallback<Integer>(){
			public Integer wrapper(ResultSet rs, int idx){
				Integer num = new Integer(0);
				try{
					num = rs.getInt("NUMS");
					return num;
				}catch(Exception e){
					e.printStackTrace();
					throw new DAOException(e);
				}
			}
		});
		if(list != null && list.size() > 0) {
//			如果存在则更新流水号
			num = ((Integer)list.get(0)).intValue() + 1;
			SvoGetnoPO con = new SvoGetnoPO();
			con.setNums(num);
			factory.update(spo, con);
		} else {
//			没有则新增
			spo.setNums(Integer.valueOf(num));
			factory.insert(spo);
		}
		returnNo.append(sclass);
		if(orgId != null)
			returnNo.append(dpo.getDealerCode().trim());
		returnNo.append(date.toString());
		if(flag != null)
			returnNo.append(flag);
		returnNo.append(num);
		return returnNo.toString();
	}
	/**
	 * 查询大区列表
	 * @return
	 */
	public static List<TmOrgPO> getTeamList(Integer orgType) {
		TmOrgPO opo = new TmOrgPO();
		opo.setOrgType(orgType);
		opo.setStatus(Constant.STATUS_ENABLE);
		return factory.select(opo);
	}
	/**
	 * 通过 CODEID 取得详细信息 
	 * @param codeId
	 * @return
	 */
	public static TcCodePO findTcCodeDetailByCodeId(Integer codeId){
		TcCodePO po = new TcCodePO();
		po.setCodeId(codeId.toString());
		List<TcCodePO> list = factory.select(po);
		if(list.size() > 0){
			return list.get(0);
		}else{
			return null;
		}		
	}
	
	public static Object getDataFromMap(Map<String,Object> map,String key){
		
		Object resultObj = null;
		if(map!=null && key!=null && map.containsKey(key)){
			resultObj = CommonUtils.checkNull(map.get(key));
		}else{
			resultObj = new String("");
		}
		return resultObj;
	}
	
	/**
	 * 根据职位查询对应用户拥有的产地权限
	 * @param poseId 职位ID
	 * @return String 产地CODE组成的字符串
	 *                格式如：yieldlyCode1+","+yieldlyCode2+...
	 *                如果没有则返回 -1 
	 */
	@SuppressWarnings("unchecked")
	public static String findYieldlyByPoseId(Long poseId){
		
		String yieldlys = "";
		
		if(poseId==null)
			return "-1";
		
		StringBuilder sql= new StringBuilder();
		sql.append("SELECT A.*\n" );
		sql.append("  FROM TM_BUSINESS_AREA A, TM_POSE_BUSINESS_AREA B\n" );
		sql.append(" WHERE 1 = 1\n" );
		sql.append("   AND A.AREA_ID = B.AREA_ID\n" );
		sql.append("   AND B.POSE_ID = ?");
		
		List<Object> paramList = new ArrayList<Object>();
		paramList.add(poseId);
		
		List<TmBusinessAreaPO> businessList = factory.select(sql.toString(), paramList, new POCallBack(factory, TmBusinessAreaPO.class));
		if(businessList!=null && businessList.size()>0){
			for (TmBusinessAreaPO tmBusinessAreaPO : businessList) {
				if(tmBusinessAreaPO.getProduceBase()!=null)
					yieldlys = yieldlys + tmBusinessAreaPO.getProduceBase() + ",";
			}
		}
		
		if(!"".equals(yieldlys) && yieldlys.length()>0)
			yieldlys = yieldlys.substring(0, yieldlys.length()-1);

		return yieldlys;
	}
	
	/**
	 * 通过车厂公司判断当前登录系统，若返回值为0表示登录系统为微车系统，1表示登录系统为轿车系统
	 * @param oemCom 当前系统的所对应的车厂公司id
	 * @return String
	 */
	public static Integer getNowSys(Long oemCom) {
		Integer flag = null ;	// 0表示微车系统，1表示轿车系统
		if(Constant.OEM_COM_SVC.equals(oemCom.toString())) {
			flag = 0 ;
		} else {
			flag = 1 ;
		}
		
		return flag ;
	}
	
	/**
	 * List 空校验
	 * @param list
	 * @return boolean
	 */
	public static boolean isNullList(List<?> list) {
		if (null == list || list.size() <= 0) {
			return true ;
		}
		
		return false ;
	}
	
	/**
	 * Map 空校验
	 * @param map
	 * @return boolean
	 */
	public static boolean isNullMap(Map<?, ?> map) {
		if (null == map || map.size() <= 0) {
			return true ;
		}
		
		return false ;
	}
	
	/******add by liuxh 20101229 增加区分公司方法********/
	@SuppressWarnings("unchecked")
	public static String getCurCompanyCode() throws Exception{
		String companyCode=Constant.COMPANY_CODE_CVS;
		String sql="SELECT COMPANY_CODE FROM COMPANY_JC_CVS";
		List list=factory.select(sql, null,new DAOCallback<String>(){
			public String wrapper(ResultSet rs, int idx){
				try{
					return rs.getString("COMPANY_CODE");					
				}catch(Exception e){
					e.printStackTrace();
					return "";
				}
			}
		});
		if(list.size()>0){
			companyCode=(String)list.get(0);
		}
		if(!companyCode.equals(Constant.COMPANY_CODE_CVS)&&!companyCode.equals(Constant.COMPANY_CODE_JC)){
			throw new BizException("错误的参数设置 companyCode:"+companyCode);
		}
		return companyCode;
	}
	/******add by liuxh 20101229 增加区分公司方法********/
}








